<?php
namespace Qwadmin\Controller;

use Vendor\Tree;
use Think\Model;

class ProxyNovelController extends ComController{
	
	public function index($sid = 0, $p = 1)
	{
		$class_list = D("novel_class")->where("is_other = 0")->select();
		
		$this->assign("class_list",$class_list);

		$other_class_list = D("novel_class")->where("is_other = 1")->select();
		
		$this->assign("other_class_list",$other_class_list);

		if(!empty($_GET["name"])) {
			$map["name"] = array("like","%".$_GET["name"]."%");
			$this->assign("search_name",$_GET["name"]);
		}
		if(!empty($_GET["class_id"])){
			$map["class_id"] = $_GET["class_id"];
			$this->assign("search_class_id",$_GET["class_id"]);
		}
		if(!empty($_GET["other_class_id"])){
			$map["other_class_id"] = $_GET["other_class_id"];
			$this->assign("search_other_class_id",$_GET["other_class_id"]);
		}
		if(!empty($_GET["from"])){
			$map["from"] = $_GET["from"];
			$this->assign("from",$_GET["from"]);
		}
		if($_GET["is_end"] != -1 && $_GET["is_end"] != ""){
			$map["is_end"] = $_GET["is_end"];
			$this->assign("is_end",$_GET["is_end"]);
		}

		if($_GET["is_shelf"] != -1 && $_GET["is_shelf"] != ""){
            $map["is_shelf"] = $_GET["is_shelf"];
            $this->assign("is_shelf",$_GET["is_shelf"]);
        }
		$order = "order_set asc,id desc";
		$xz = 1;
		if(!empty($_GET["order_set"]))
			$order= "order_set asc";
			elseif(!empty($_GET["flow_set"]))
			$order= "flow_set asc";
			elseif (!empty($_GET["pay_count"]))
            $order= "count desc";
			elseif (!empty($_GET["click_count"]))
            $order= "click_count desc";
			elseif (!empty($_GET["manp"])){
			    $xz = x;
                $condition = "where other_class_name = '男生'";
            }
            elseif (!empty($_GET["womanp"])){
			    $xz = o;
                $condition = "where other_class_name = '女生'";
            }
            elseif (!empty($_GET["is_flag"])){
                $xz = h;
                $condition = "where is_flag = 1";
            }

			$p = $_GET["p"] ? $_GET["p"] : 1;
			$novel = M('Novel');
			$pagesize = 20;
			$offset = $pagesize * ($p - 1);
			$count = $novel->query("select count(1) as num from qw_novel $condition");
			$count = $count[0][num];
            $list = $novel->query("select a.*,(SELECT count(1)*0.14 as count FROM `qw_user_buy` as b where b.novel_id = a.id) as count,(select count(1) as chapter from `qw_novel_chapter` as c where c.novel_id = a.id) as chapter  from qw_novel as a $condition ORDER BY $order limit $offset,$pagesize");
            if (!empty($_GET["name"])){
                $name = $_GET["name"];
                $condition = "where name like '%$name%'";
                $list = $novel->query("select a.*,(SELECT count(1)*0.14 as count FROM `qw_user_buy` as b where b.novel_id = a.id) as count,(select count(1) as chapter from `qw_novel_chapter` as c where c.novel_id = a.id) as chapter  from qw_novel as a $condition limit $offset,$pagesize");
                $count = $novel->query("select count(1) as num from qw_novel $condition");
                $count = $count[0][num];
            }
            foreach($list as $x){
				$dir="<img src= ".$x['img']." /> ";
			}
			$page = new \Think\Page($count, $pagesize);
			$page = $page->show();
			$this->assign('xz',$xz);
			$this->assign('list', $list);
			$this->assign('page', $page);
			$this->assign('xz',$xz);
			$this->display();

	}
	
	/**
	 * 经纪人小说章节管理
	 * */
	public function chapter($p = 1){

	    //小说的推广文案
        if (isset($_GET["show"])){
            //本章id
            $chapter_id = $_GET['chapter_id'];
            //章节数
            $chaptera = $_GET['order_set'];
            $idd = $_GET['chapter_id']+1;
            //下一篇文章章节内容
            $next_article = D("novel_chapter")->field('novel_id,chapter,order_set,title,id')->where('id='.$idd)->find();
            $this->assign('next',$next_article);
            $novel_id = $_GET["show"];
            $show = M("novel_chapter");
            $list = $show->query("select id,novel_mini_img,content,chapter,title from qw_novel_chapter WHERE novel_id=$novel_id limit $chaptera");
            //$lists = $show->query("select * from qw_novel_chapter WHERE novel_id=$novel_id limit $chaptera");
            //文案标题条数
            $count1 = D("title")->count();
            //文案标题
            $title_wa = D('title')->where('id = '.rand(1,$count1))->field('content')->find();
            //封面所有title
            $titles = D('title')->field('content')->select();
            //文案封面数量
            $count2 = D("cover")->count();
            $cover_wa = D("cover")->where("id = ".rand(1,$count2))->field('url')->find();
            //封面所有url
            $covers = D("cover")->field('url')->select();
            //正文模板
            $countzw = D("zwmodel")->count();
            $zwmodel = D("zwmodel")->where("id = 1")->find();
            $zwmodel['content'] = htmlentities($zwmodel['content']);
            //正文模板图标
            $zwmodelimg = D("zwmodel")->field('pic,id')->select();
            //原文模板数量
            $count3 = D('ywydmodel')->count();
            //随机原文模板
            $ywmb = D('ywydmodel')->where("id = ".rand(1,$count3))->field('ywnr')->find();
            //原文所有模版
            $ywmb_all = D('ywydmodel')->field('pic,id')->select();
            $this->assign('ywmb',$ywmb);
            $this->assign('ywmb_all',$ywmb_all);
            $uid = $_SESSION['uid'];
            $this->assign('uid',$uid);
            $this->assign('zwmodel',$zwmodel);
            $this->assign('img',$zwmodelimg);
            $this->assign('list',$list);
            $this->assign('count',$chaptera);
            $this->assign('title',$title_wa);
            $this->assign('titles',$titles);
            $this->assign('cover',$cover_wa);
            $this->assign('covers',$covers);
            $this->assign('domain',C("FILE_HOST_PATH"));
            $this->display('show');die;
        }
        //点击文章标题传入的js
        if ($_GET['cptid']){
            $cptid = $_GET['cptid'];
            $novel_id = $_GET['novel_id'];
            $chapter = M('novel_chapter');
            $data = D('novel_chapter')->query("select * from qw_novel_chapter where order_set = $cptid and novel_id = $novel_id");
            echo $this->ajaxReturn($data);
        }
        if ($_GET['cpid']){
            $cpid = $_GET['cpid'];
            $novel = $_GET['novel_id'];
            $data = D('novel_chapter')->query("select * from qw_novel_chapter where order_set = $cpid and novel_id = $novel");
            echo $this->ajaxReturn($data);

        }
        if ($_GET['ccpid']){
            $novel_id = $_GET['novel_id'];
            $chapter = M('novel_chapter');
            $count = $chapter->where('novel_id='.$novel_id)->count();
            $cptid = $_GET['ccpid'];
            $chapter = $_GET['chapter'];
            $st = mb_strcut($chapter,3,8);
            $stt = strrev($st);
            $stt = mb_strcut($stt,3,4);
            $stt = strrev($stt);
            if ($stt >  $count ){
                echo $this->ajaxReturn(0);
            }else{
                $cptid = $cptid+1;
                //var_dump($cptid);die();
                $data = D("novel_chapter")->where("id=".$cptid)->select();

                //$data = $chapter->query("select * from qw_novel_chapter where id = $cptid");
                //var_dump($data);die;
                echo $this->ajaxReturn($data);
            }

        }
        //切换正文模板
        if (isset($_GET['show_id'])){
            $list = D('zwmodel')->where('id='.$_GET['show_id'])->find(); 
            //$list['content'] = htmlentities($list['content']);
            echo $this->ajaxReturn($list);
        }
        //切换原文模板
        if (isset($_GET['ywmb'])){
            $all = D('ywydmodel')->where('id='.$_GET['ywmb'])->find();
            echo $this->ajaxReturn($all);
        }
		if(isset($_GET["id"])){
            $this->assign('uid',$_SESSION['uid']);
            $ar = D('auth_group_access')->field('group_id')->where('uid='.$_SESSION['uid'])->find();
            if ($ar['group_id'] == 10) {
                $ismeiti = 1;
            }
            $this->assign('ismeiti',$ismeiti);

			$id = $_GET["id"];
            $chapter_last = D("novel_chapter")->where('novel_id='.$id)->order("order_set desc")->find();
            $this->assign('chapter_last',$chapter_last['order_set']);
			$novel = M('novel')->where(array('id'=>$id))->find();
			if($novel['subscribe_chapter'] <= 6){
                $subscribe_chapter = $novel['subscribe_chapter']+1;
            }else{
                $subscribe_chapter=6;
            }
			$this->assign('novel',$novel);
			$this->assign('subscribe_chapter',$subscribe_chapter);
			$this->assign("novel_id",$id);
			$p = intval($p) > 0 ? $p : 1;
			$this->assign('p',$p);
			$chapter= M('novel_chapter');
			$pagesize = 15;
			$offset = $pagesize * ($p - 1);
			$map["novel_id"] = $id;
			$count = $chapter->where($map)->count();
			header("Content-type:text/html;charset=utf-8");
			$list = $chapter->where($map)->order("order_set asc")->limit($offset . ','.$pagesize)->select();
			$page = new \Think\Page($count, $pagesize);
			$page = $page->show();
			$this->assign('list', $list);
			$this->assign('page', $page);
			//查询小说连接
			//如果没有生成小说连接默认在此本小说的第一章
			//$lmap["proxy_id"] = $_SESSION["uid"];
			$rs_g = D("auth_group_access")->where("uid=".$_SESSION["uid"])->find();
			$rs = D("auth_group")->where("id=".$rs_g["group_id"])->find();
			if($rs["title"] == "经纪人") {
				$lmap["proxy_id"] = $_SESSION["uid"];
			}
			else{
				$mem = D("member")->where("uid=".$_SESSION["uid"])->find();
				//print_r($mem);die;
				$lmap["proxy_id"] = $mem["par_id"];
			}

			$lmap["novel_id"] = $novel["id"];
			$link = D("proxy_link")->where($lmap)->find();
			//echo D("proxy_link")->getLastSql();die;
			if(!empty($link))
				$this->assign("link", $link);
			$this->display();
		}
		else{
			$this->error('请选择一篇小说',"index.html");
		}

	}
	
	/**
	 * 媒体人小说管理
	 * */
	public function medianovel($p = 1){
		$class_list = D("novel_class")->where("is_other = 0")->select();
		
		$this->assign("class_list",$class_list);
		
		$other_class_list = D("novel_class")->where("is_other = 1")->select();
		
		$this->assign("other_class_list",$other_class_list);
		
		//获得上线经济人的信息
		$proxy_info = D("member")->where("uid=".$_SESSION["uid"])->find();
		
		if(!empty($_GET["name"])) {
			$map["name"] = array("like","%".$_GET["name"]."%");
			$this->assign("search_name",$_GET["name"]);
		}
		if(!empty($_GET["class_id"])){
			$map["class_id"] = $_GET["class_id"];
			$this->assign("search_class_id",$_GET["class_id"]);
		}
		if(!empty($_GET["other_class_id"])){
			$map["other_class_id"] = $_GET["other_class_id"];
			$this->assign("search_other_class_id",$_GET["other_class_id"]);
		}
		if(!empty($_GET["from"])){
			$map["from"] = $_GET["from"];
			$this->assign("from",$_GET["from"]);
		}
		if($_GET["is_end"] != -1 && $_GET["is_end"] != ""){
			$map["is_end"] = $_GET["is_end"];
			$this->assign("is_end",$_GET["is_end"]);
		}
		
		if($_GET["is_shelf"] != -1 && $_GET["is_shelf"] != ""){
			$map["is_shelf"] = $_GET["is_shelf"];
			$this->assign("is_shelf",$_GET["is_shelf"]);
		}
		$xz = 1;
        if (!empty($_GET["manp"])){
            $xz = x;
            $condition = "where other_class_name = '男生'";
        }
        elseif (!empty($_GET["womanp"])){
            $xz = o;
            $condition = "where other_class_name = '女生'";
        }
        elseif (!empty($_GET["is_flag"])){
            $xz = h;
            $condition = "where is_flag = 1";
        }
        /*elseif (!empty($_GET["name"])){
            $name = $_GET["name"];
            $condition = "where name like '%$name%'";
        }*/
        $this->assign("xz",$xz);
		
		$order = "order_set asc,id desc";

		if(!empty($_GET["order_set"]))
			$order= "order_set asc";
			elseif(!empty($_GET["flow_set"]))
			$order= "flow_set asc";
            elseif (!empty($_GET["pay_count"]))
                $order= "count desc";
            elseif (!empty($_GET["click_count"]))
                $order= "click_count desc";
			$p = $_GET["p"] ? $_GET["p"] : 1;
			$novel = M('Novel');
			$pagesize = 20;
			$offset = $pagesize * ($p - 1);
            $count = $novel->query("select count(1) as num from qw_novel $condition");
            $count = $count[0][num];
            $list = $novel->query("select a.*,(SELECT count(1)*0.14 as count FROM `qw_user_buy` as b where b.novel_id = a.id) as count,(select count(1) as chapter from `qw_novel_chapter` as c where c.novel_id = a.id) as chapter  from qw_novel as a $condition ORDER BY $order limit $offset,$pagesize");
            if (!empty($_GET["name"])){
                $name = $_GET["name"];
                $condition = "where name like '%$name%'";
                $count = $novel->query("select count(1) as num from qw_novel $condition");
                $list = $novel->query("select a.*,(SELECT count(1)*0.14 as count FROM `qw_user_buy` as b where b.novel_id = a.id) as count,(select count(1) as chapter from `qw_novel_chapter` as c where c.novel_id = a.id) as chapter  from qw_novel as a $condition ORDER BY $order limit $offset,$pagesize");
                $count = $count[0][num];
            }
			foreach($list as $key=>$item){
				$dir="<img src= ".$item['img']." /> ";
				
				//获得推广连接
				$lmap["novel_id"] = $item["id"];
				$lmap["proxy_id"] = $proxy_info["par_id"];
				$link_rs = D("proxy_link")->where($lmap)->find();				
				
				if(!empty($link_rs)){
					$list[$key]["link"] = "当前生成连接在 {$link_rs["novel_name"]}的{$link_rs["chapter"]} 地址是 http://qikaism.cn/Home/Novel/show/id/{$link_rs["chapter_id"]}/novel_id/{$link_rs["novel_id"]}/uid/{$_SESSION["uid"]}"; 
				}
				else{
					//获得小说第一章
					$chapter_rs = D("novel_chapter")->where("novel_id=".$item["id"])->find();
					$list[$key]["link"] = "当前生成连接在 {$chapter_rs["novel_name"]}的{$chapter_rs["chapter"]} 地址是 http://qikaism.cn/Home/Novel/show/id/{$chapter_rs["id"]}/novel_id/{$chapter_rs["novel_id"]}/uid/{$_SESSION["uid"]}";
				}
			}
			$page = new \Think\Page($count, $pagesize);
			$page = $page->show();
			$this->assign('list', $list);
			$this->assign('page', $page);
			$this->display();


	}
	
	/**
	 * 创建连接
	 * */
	public function createlink(){
		if(isset($_GET["id"])){
			$id = $_GET["id"];

			$chapter = D("novel_chapter")->where("id=%d",array($id))->find();
			$data["novel_id"] = $chapter["novel_id"];
			$data["novel_name"] = $chapter["novel_name"];
			$data["chapter_id"] = $chapter["id"];
			$data["chapter_name"] = $chapter["title"];
			$data["chapter"] = $chapter["chapter"];
			$data["proxy_id"] = $_SESSION["uid"];
			
			//判断此小说是否已经生成过了
			$map["novel_id"] = $chapter["novel_id"];
			//判断SESSION["uid"]是否是经济人的ID，如果不是就就去查询他的上级id
			$rs_g = D("auth_group_access")->where("uid=".$_SESSION["uid"])->find();
			$rs = D("auth_group")->where("id=".$rs_g["group_id"])->find();
			
			if($rs["title"] == "经纪人")
				$map["proxy_id"] = $_SESSION["uid"];
			else{
				$mem = D("member")->where("uid=".$_SESSION["uid"])->find();
				//print_r($mem);die;
				$map["proxy_id"] = $mem["par_id"];
				$data["proxy_id"] = $mem["par_id"];
			}
			$rs = D("proxy_link")->where($map)->find();
			if(empty($rs))
				D("proxy_link")->add($data);
			else{
				D("proxy_link")->where("id=".$rs["id"])->save($data);
			} 
				
			$this->success("生成成功","/Qwadmin/ProxyNovel/chapter/id/".$chapter["novel_id"]);
		}
		else{
			$this->error('请选择一章节小说');
		}
	}
	
	/**
	 * 订单统计
	 * */
	public function count(){
		$order = M("order");
		//获得经纪人手下的媒体人的UID字符串
		$media = D("member")->field("uid")->where("par_id=".$_SESSION["uid"])->select();
		$media_uid = "";
		foreach($media as $key=>$item){
			if($key < count($media) - 1)
				$media_uid .= $item["uid"].",";
			else 
				$media_uid .= $item["uid"];
		}			
		
		//echo $media_uid;die;
		
		//当日统计
		$daynow=date("Y-m-d");
		$data["already_paid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$daynow}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//当前时间充值的用户数量
		$data["already_paid"] = $data["already_paid"][0]["count"];
		$data["total"] = $order->query("select sum(money) as money from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$daynow}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//当前时间充值金额总数
		$data["total"] = $data["total"][0]["money"] / 100;
		$data["unpaid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.addtime like '{$daynow}%' and a.status = 0 and b.proxy_id in ({$media_uid})");//当前时间未充值的用户数量
		$data["unpaid"] = $data["unpaid"][0]["count"];
		$result["rate"]=$data["already_paid"]/($data["already_paid"]+$data["unpaid"]);
		$data["rate"]=floor($result["rate"]*10000)/10000*100;//当前的完成率
		$this->assign("pays_day",$data);
		$this->assign("Today",$daynow);
		//昨日统计
		$todaynow=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-1,date("Y")));
		$consequence["addtime"] = array("like",$todaynow."%");
		$finish["already_paid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$todaynow}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//昨天充值的用户数量
		$finish["already_paid"] = $finish["already_paid"][0]["count"];
		$finish["total"] = $order->query("select sum(money) as money from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$todaynow}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//昨天充值金额总数
		$finish["total"] = $finish["total"][0]["money"] / 100;
		$finish["unpaid"]=$order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.addtime like '{$todaynow}%' and a.status = 0 and b.proxy_id in ({$media_uid})");;//昨天未充值的用户数量
		$finish["unpaid"] = $finish["unpaid"][0]["count"];
		$consequence["rate"]=$finish["already_paid"]/($finish["already_paid"]+$finish["unpaid"]);
		$finish["rate"]=floor($consequence["rate"]*10000)/10000*100;//昨天的完成率
		$this->assign("pays_today",$finish);
		$this->assign("Yesterday",$todaynow);
		//前天统计
		$before_yesterday=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-2,date("Y")));
		$finish_before_yesterday["already_paid"]= $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$before_yesterday}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//前天充值的用户数量
		$finish_before_yesterday["already_paid"] = $finish_before_yesterday["already_paid"][0]["count"];
		$finish_before_yesterday["total"] = $order->query("select sum(money) as money from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$before_yesterday}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//前天充值金额总数
		$finish_before_yesterday["total"] = $finish_before_yesterday["total"][0]["money"] / 100;
		$finish_before_yesterday["unpaid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.addtime like '{$before_yesterday}%' and a.status = 0 and b.proxy_id in ({$media_uid})");//前天未充值的用户数量
		$finish_before_yesterday["unpaid"] = $finish_before_yesterday["unpaid"][0]["count"];
		$consequence_before_yesterday["rate"]=$finish_before_yesterday["already_paid"]/($finish_before_yesterday["already_paid"]+$finish_before_yesterday["unpaid"]);
		$finish_before_yesterday["rate"]=floor($consequence_before_yesterday["rate"]*10000)/10000*100;//前天的完成率
		$this->assign("pays_before_yesterday",$finish_before_yesterday);
		$this->assign("before_yesterday",$before_yesterday);
		//大前天统计
		$days_ago=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-3,date("Y")));
		$finish_days_ago["already_paid"]= $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$days_ago}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//大前天充值的用户数量
		$finish_days_ago["already_paid"] = $finish_days_ago["already_paid"][0]["count"];
		$finish_days_ago["total"] = $order->query("select sum(money) as money from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$days_ago}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//大前天充值金额总数
		$finish_days_ago["total"] = $finish_days_ago["total"][0]["money"] / 100;
		$finish_days_ago["unpaid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.addtime like '{$days_ago}%' and a.status = 0 and b.proxy_id in ({$media_uid})");//大前天未充值的用户数量
		$finish_days_ago["unpaid"] = $finish_days_ago["unpaid"][0]["count"];
		$consequence_days_ago["rate"]=$finish_days_ago["already_paid"]/($finish_days_ago["already_paid"]+$finish_days_ago["unpaid"]);
		$finish_days_ago["rate"]=floor($consequence_days_ago["rate"]*10000)/10000*100;//大前天的完成率
		$this->assign("pays_days_ago",$finish_days_ago);
		$this->assign("days_ago",$days_ago);
		//当月统计
		$monthnow=date("Y-m");
		$finally["already_paid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$monthnow}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//当月时间充值的用户数量
		$finally["already_paid"] = $finally["already_paid"][0]["count"];
		$finally["total"] = $order->query("select sum(money) as money from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.paytime like '{$monthnow}%' and a.status = 1 and b.proxy_id in ({$media_uid})");//当月时间充值金额总数
		$finally["total"] = $finally["total"][0]["money"] / 100;
		$finally["unpaid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.addtime like '{$monthnow}%' and a.status = 0 and b.proxy_id in ({$media_uid})");//当月时间未充值的用户数量
		$finally["unpaid"] = $finally["unpaid"][0]["count"];
		$outcome["rate"]=$finally["already_paid"]/($finally["already_paid"]+$finally["unpaid"]);
		$finally["rate"]=floor($outcome["rate"]*10000)/10000*100;//当月的完成率
		$this->assign("pays_month",$finally);
		//累计统计
		$Last["already_paid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.status = 1 and b.proxy_id in ({$media_uid})");//总共充值的用户数量
		$Last["already_paid"] = $Last["already_paid"][0]["count"];
		$Last["total"] = $order->query("select sum(money) as money from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.status = 1 and b.proxy_id in ({$media_uid})");//总共充值金额总数
		$Last["total"] = $Last["total"][0]["money"] / 100;
		$Last["unpaid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.status = 0 and b.proxy_id in ({$media_uid})");//总共未充值的用户数量
		$Last["unpaid"] = $Last["unpaid"][0]["count"];
		$ultimate["rate"]=$Last["already_paid"]/($Last["already_paid"]+$Last["unpaid"]);
		$Last["rate"]=floor($ultimate["rate"]*10000)/10000*100;//总共的完成率
		$this->assign("pays_altogether",$Last);


		$this->display();
//		var_dump($json);die;
		//dump($data);
	}
	/**
	 * 用户统计
	 * */
	
	public function statistics(){
		//查询经纪人的下线所有媒体人
		$media_list = D("member")->where("par_id=".$_SESSION["uid"])->select();
		//print_r($media_list);die;
		
		$user=M(user);
		$model = M("Member");
		$uid = session('uid');
		$uss = $model->where(array('uid'=>$uid))->select();
		$data_day = array("man"=>0,"woman"=>0,"total"=>0);
		$data_today= array("man"=>0,"woman"=>0,"total"=>0);
		$data_byesterday = array("man"=>0,"woman"=>0,"total"=>0);
		$data_days_ago = array("man"=>0,"woman"=>0,"total"=>0);
		$data_days_greatly = array("man"=>0,"woman"=>0,"total"=>0);
		$data_month= array("man"=>0,"woman"=>0,"total"=>0);
		$data_overall = array("man"=>0,"woman"=>0,"total"=>0);
		
		foreach($media_list as $key=>$item) {
			//今日统计
			$daynow=date("Y-m-d");
			$where_man["addtime"]=array("like",$daynow."%");
			$where_man["sex"]=1;			
			$where_man["proxy_id"]=$item["uid"];
			$where_man["subscribe"]=1;
			$where_woman["sex"]=2;
			$where_woman["addtime"]=array("like",$daynow."%");
			$where_woman["proxy_id"]=$item["uid"];
			$where_woman["subscribe"]=1;
			$data_day["man"] += $user->where($where_man)->count();//当日新增男性用户
			$data_day["woman"] += $user->where($where_woman)->count();//当日新增女性用户
			$data_day["total"] += $data_day["man"] + $data_day["woman"];//当日新增用户总量
			$this->assign("added_day",$data_day);
			$this->assign("Today",$daynow);
			
			//昨日统计
			$todaynow=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-1,date("Y")));
			$where_man_today["addtime"]=array("like",$todaynow."%");
			$where_man_today["sex"]=1;
			$where_man_today["proxy_id"]=$item["uid"];
			$where_man_today["subscribe"]=1;
			$where_woman_today["sex"]=2;
			$where_woman_today["addtime"]=array("like",$todaynow."%");
			$where_woman_today["proxy_id"]=$item["uid"];
			$where_woman_today["subscribe"]=1;
			$data_today["man"]+=$user->where($where_man_today)->count();//昨日新增男性用户
			$data_today["woman"]+=$user->where($where_woman_today)->count();//昨日新增女性用户
			$data_today["total"]+=$data_today["man"]+$data_today["woman"];//昨日新增用户总量
			$this->assign("added_today",$data_today);
			$this->assign("Todaynow",$todaynow);
			
			//前天统计
			$before_yesterdaynow=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-2,date("Y")));
			$where_man_byesterday["addtime"]=array("like",$before_yesterdaynow."%");
			$where_man_byesterday["sex"]=1;
			$where_man_byesterday["proxy_id"]=$item["uid"];
			$where_man_byesterday["subscribe"]=1;
			$where_woman_byesterday["sex"]=2;
			$where_woman_byesterday["addtime"]=array("like",$before_yesterdaynow."%");
			$where_woman_byesterday["proxy_id"]=$item["uid"];
			$where_woman_byesterday["subscribe"]=1;
			$data_byesterday["man"]+=$user->where($where_man_byesterday)->count();//前天新增男性用户
			$data_byesterday["woman"]+=$user->where($where_woman_byesterday)->count();//前天新增女性用户
			$data_byesterday["total"]+=$data_byesterday["man"]+$data_byesterday["woman"];//前天新增用户总量
			$this->assign("byesterday",$data_byesterday);
			$this->assign("before_yesterdaynow",$before_yesterdaynow);
			
			//大前天统计
			$days_ago=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-3,date("Y")));
			$where_man_days_ago["addtime"]=array("like",$days_ago."%");
			$where_man_days_ago["sex"]=1;
			$where_man_days_ago["proxy_id"]=$item["uid"];
			$where_man_days_ago["subscribe"]=1;
			$where_woman_days_ago["sex"]=2;
			$where_woman_days_ago["addtime"]=array("like",$days_ago."%");
			$where_woman_days_ago["proxy_id"]=$item["uid"];
			$where_woman_days_ago["subscribe"]=1;
			$data_days_ago["man"]+=$user->where($where_man_days_ago)->count();//大前天新增男性用户
			$data_days_ago["woman"]+=$user->where($where_woman_days_ago)->count();//大前天新增女性用户
			$data_days_ago["total"]+=$data_days_ago["man"]+$data_days_ago["woman"];//大前天新增用户总量
			$this->assign("user_days_ago",$data_days_ago);
			$this->assign("days_agonow",$days_ago);
			
			//大大前天统计
			$days_greatly=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-4,date("Y")));
			$where_man_days_greatly["addtime"]=array("like",$days_greatly."%");
			$where_man_days_greatly["sex"]=1;
			$where_man_days_greatly["proxy_id"]=$item["uid"];
			$where_man_days_greatly["subscribe"]=1;
			$where_woman_days_greatly["sex"]=2;
			$where_woman_days_greatly["addtime"]=array("like",$days_greatly."%");
			$where_woman_days_greatly["proxy_id"]=$item["uid"];
			$where_woman_days_greatly["subscribe"]=1;
			$data_days_greatly["man"]+=$user->where($where_man_days_greatly)->count();//大大前天新增男性用户
			$data_days_greatly["woman"]+=$user->where($where_woman_days_greatly)->count();//大大前天新增女性用户
			$data_days_greatly["total"]+=$data_days_greatly["man"]+$data_days_greatly["woman"];//大大前天新增用户总量
			$this->assign("user_days_greatly",$data_days_greatly);
			$this->assign("days_greatly",$days_greatly);
			
			//当月统计
			$daymonth=date("Y-m");
			$where_man_month["addtime"]=array("like",$daymonth."%");
			$where_man_month["sex"]=1;
			$where_man_month["proxy_id"]=$item["uid"];
			$where_man_month["subscribe"]=1;
			$where_woman_today["sex"]=2;
			$where_woman_today["addtime"]=array("like",$daymonth."%");
			$where_woman_today["proxy_id"]=$item["uid"];
			$where_woman_today["subscribe"]=1;
			$data_month["man"]+=$user->where($where_man_month)->count();//当月新增男性用户
			$data_month["woman"]+=$user->where($where_woman_today)->count();//当月新增女性用户
			//echo $user->getLastSql();die;
			$data_month["total"]+=$data_month["man"]+$data_month["woman"];//当月新增用户总量
			$this->assign("added_month",$data_month);
			
			//累计统计
			$where_man_overall["sex"]=1;
			$where_man_overall["proxy_id"]=$item["uid"];
			$where_man_overall["subscribe"]=1;
			$where_woman_overall["sex"]=2;
			$where_woman_overall["proxy_id"]=$item["uid"];
			$where_woman_overall["subscribe"]=1;
			$data_overall["man"] += $user->where($where_man_overall)->count();//总共新增男性用户
			$data_overall["woman"] += $user->where($where_woman_overall)->count();//总共新增女性用户
			$data_overall["total"] += intval($data_overall["man"])+intval($data_overall["woman"]);//总共新增用户总量
			$this->assign("added_overall",$data_overall);


// 			if(!empty($data_overall["total"])) {
// 				print_r($item)."<br>";
// 				print_r($data_overall);
// 				die;
// 			}
		}
		$this->display();
	}
	
	/**
	 * 添加媒体人
	 * */
	public function addmedia(){
		if($_POST){
			//获取当前用户的信息
			$user_info = D("member")->field("user")->where("uid=".$_SESSION["uid"])->find();
			$usergroup = M('auth_group')->field('id')->where("title='媒体人'")->find();
			$data["user"] = $_POST["user"];
			$data["password"] = password($_POST["password"]);
			$data["head"] = "/Public/attached/201601/1453389194.png";
			$data["par_id"] = $_SESSION["uid"];
			$data["group_id"] = $usergroup["id"];
			$data["t"] = time();
			$data["limit_time"] = $_POST["limit_time"];
			$uid = $_POST["uid"];
			
			if (empty($uid)) {
				if ($data["user"] == '') {
					$this->error('用户名称不能为空！');
				}
				if (empty($_POST["password"])) {
					$this->error('用户密码不能为空！');
				}
				if (M('member')->where("user='%s'",array($_POST["user"]))->count()) {
					$this->error('用户名已被占用！');
				}
				$uid = M('member')->data($data)->add();
				M('auth_group_access')->data(array('group_id' => $data["group_id"], 'uid' => $uid))->add();
				addlog("经纪人：".$user_info["user"].'新增媒体人会员：' . $data["user"]);
			} else {				
				if (empty($_POST["password"])) {
					unset($data["password"]);
				}
				unset($data["user"]);
				addlog("经纪人：".$user_info["user"].'编辑媒体人会员：' . $data["user"]);
				M('member')->data($data)->where("uid=%d",array($uid))->save();
				
			}
			$this->success('操作成功！');
		}
		else{
			if($_GET["uid"]){
				$media = D("member")->field("uid,user,limit_time")->where("uid=%d",array($_GET["uid"]))->find();
				$this->assign("media", $media);
			}			
			$this->display();
		}		
	}
	
	/**
	 * 媒体人列表
	 * 只允许经纪人查看
	 * */
	public function medialist(){
		$p = isset($_GET['p']) ? intval($_GET['p']) : '1';
		$field = isset($_GET['field']) ? $_GET['field'] : '';
		$keyword = isset($_GET['keyword']) ? htmlentities($_GET['keyword']) : '';
		$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
		$where = '';
		//echo $keyword.$field;die;
		
		$prefix = C('DB_PREFIX');
		if ($order == 'asc') {
			$order = "{$prefix}member.t asc";
		} elseif (($order == 'desc')) {
			$order = "{$prefix}member.t desc";
		} else {
			$order = "{$prefix}member.uid asc";
		}
		if ($keyword <> '') {
			if ($field == 'user') {
				$where = "{$prefix}member.user LIKE '%$keyword%'";
			}
			if ($field == 'phone') {
				$where = "{$prefix}member.phone LIKE '%$keyword%'";
			}
		}
		if(empty($where)){
			$where = "{$prefix}member.par_id = {$_SESSION["uid"]}";
		}
		else{
			$where .= " and {$prefix}member.par_id = {$_SESSION["uid"]}";
		}
		
		
		//echo $where;die;
		
		
		$user = M('member');
		$pagesize = 10;#每页数量
		$offset = $pagesize * ($p - 1);//计算记录偏移量
		$count = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title")
		->order($order)
		->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid")
		->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}auth_group_access.group_id")
		->where($where)
		->count();
		
		$list = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title")
		->order($order)
		->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid")
		->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}auth_group_access.group_id")
		->where($where)
		->limit($offset . ',' . $pagesize)
		->select();
		//$user->getLastSql();die;
		$page = new \Think\Page($count, $pagesize);
		$page = $page->show();
		//print_r($list);die;
		foreach($list as $key=>$item){
			$total = M()->query("select sum(money) as money from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.status = 1 and b.proxy_id in ('{$item["uid"]}')");//总共充值金额总数
			$total = $total[0]["money"] / 100;
			$list[$key]["total"] = $total;
		}		
		
		$this->assign('list', $list);
		$this->assign('page', $page);
		$group = M('auth_group')->field('id,title')->select();
		$this->assign('group', $group);
		$this->display();
	}
	
	/**
	 * 媒体人的订单统计
	 * */
	public function mediacount(){
		$order = M("order");
		
		//获得经纪人手下的媒体人的UID字符串
		$media = D("member")->where("uid=".$_SESSION["uid"])->find();
		
		//获得媒体人发展用户的第一笔充值记录
		//$rs = $order->query("select * from qw_order as a left join qw_user as b on a.open_id=b.open_id where a.status = 1 and b.proxy_id={$_SESSION["uid"]} limit 0,1");
		//print_r($rs);die;
		//$start_time = $rs[0]["paytime"];
		//$end_time = date("Y-m-d H:i:s", (strtotime($start_time) + $media["limit_time"] * 3600) );
		//echo $end_time;die;
		
		//累计统计
		$Last["already_paid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.status = 1 and UNIX_TIMESTAMP(a.paytime) <= UNIX_TIMESTAMP(b.addtime) + (3600 * {$media["limit_time"]}) and b.proxy_id in ('{$_SESSION["uid"]}')");//总共充值的用户数量
		$Last["already_paid"] = $Last["already_paid"][0]["count"];
		$Last["total"] = $order->query("select sum(money) as money from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.status = 1 and UNIX_TIMESTAMP(a.paytime) <= UNIX_TIMESTAMP(b.addtime) + (3600 * {$media["limit_time"]}) and b.proxy_id in ('{$_SESSION["uid"]}')");//总共充值金额总数
		//echo $order->getLastSql();die;
		$Last["total"] = $Last["total"][0]["money"] / 100;
		$Last["unpaid"] = $order->query("select count(*) as count from qw_order as a left join qw_user as b on a.open_id = b.open_id where a.status = 0 and UNIX_TIMESTAMP(a.paytime) <= UNIX_TIMESTAMP(b.addtime) + (3600 * {$media["limit_time"]}) and b.proxy_id in ('{$_SESSION["uid"]}')");//总共未充值的用户数量
		$Last["unpaid"] = $Last["unpaid"][0]["count"];
		$ultimate["rate"]=$Last["already_paid"]/($Last["already_paid"]+$Last["unpaid"]);
		$Last["rate"]=floor($ultimate["rate"]*10000)/10000*100;//总共的完成率
		$this->assign("pays_altogether",$Last);
		$this->display();
	}
	
	/**
	 * 媒体人的人员统计
	 * */
	public function mediastatistics(){
		//查询经纪人的下线所有媒体人
		$media_list = D("member")->where("uid=".$_SESSION["uid"])->select();
		//print_r($media_list);die;
		
		$user=M(user);
		$model = M("Member");
		$uid = session('uid');
		$uss = $model->where(array('uid'=>$uid))->select();
		$data_day = array("man"=>0,"woman"=>0,"total"=>0);
		$data_today= array("man"=>0,"woman"=>0,"total"=>0);
		$data_byesterday = array("man"=>0,"woman"=>0,"total"=>0);
		$data_days_ago = array("man"=>0,"woman"=>0,"total"=>0);
		$data_days_greatly = array("man"=>0,"woman"=>0,"total"=>0);
		$data_month= array("man"=>0,"woman"=>0,"total"=>0);
		$data_overall = array("man"=>0,"woman"=>0,"total"=>0);
		
		foreach($media_list as $key=>$item) {
			//今日统计
			$daynow=date("Y-m-d");
			$where_man["addtime"]=array("like",$daynow."%");
			$where_man["sex"]=1;
			$where_man["proxy_id"]=$item["uid"];
			$where_man["subscribe"]=1;
			$where_woman["sex"]=2;
			$where_woman["addtime"]=array("like",$daynow."%");
			$where_woman["proxy_id"]=$item["uid"];
			$where_woman["subscribe"]=1;
			$data_day["man"]+=$user->where($where_man)->count();//当日新增男性用户
			$data_day["woman"]+=$user->where($where_woman)->count();//当日新增女性用户
			$data_day["total"]+=$data_day["man"]+$data_day["woman"];//当日新增用户总量
			$this->assign("added_day",$data_day);
			$this->assign("Today",$daynow);
			
			//昨日统计
			$todaynow=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-1,date("Y")));
			$where_man_today["addtime"]=array("like",$todaynow."%");
			$where_man_today["sex"]=1;
			$where_man_today["proxy_id"]=$item["uid"];
			$where_man_today["subscribe"]=1;
			$where_woman_today["sex"]=2;
			$where_woman_today["addtime"]=array("like",$todaynow."%");
			$where_woman_today["proxy_id"]=$item["uid"];
			$where_woman_today["subscribe"]=1;
			$data_today["man"]+=$user->where($where_man_today)->count();//昨日新增男性用户
			$data_today["woman"]+=$user->where($where_woman_today)->count();//昨日新增女性用户
			$data_today["total"]+=$data_today["man"]+$data_today["woman"];//昨日新增用户总量
			$this->assign("added_today",$data_today);
			$this->assign("Todaynow",$todaynow);
			
			//前天统计
			$before_yesterdaynow=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-2,date("Y")));
			$where_man_byesterday["addtime"]=array("like",$before_yesterdaynow."%");
			$where_man_byesterday["sex"]=1;
			$where_man_byesterday["proxy_id"]=$item["uid"];
			$where_man_byesterday["subscribe"]=1;
			$where_woman_byesterday["sex"]=2;
			$where_woman_byesterday["addtime"]=array("like",$before_yesterdaynow."%");
			$where_woman_byesterday["proxy_id"]=$item["uid"];
			$where_woman_byesterday["subscribe"]=1;
			$data_byesterday["man"]+=$user->where($where_man_byesterday)->count();//前天新增男性用户
			$data_byesterday["woman"]+=$user->where($where_woman_byesterday)->count();//前天新增女性用户
			$data_byesterday["total"]+=$data_byesterday["man"]+$data_byesterday["woman"];//前天新增用户总量
			$this->assign("byesterday",$data_byesterday);
			$this->assign("before_yesterdaynow",$before_yesterdaynow);
			
			//大前天统计
			$days_ago=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-3,date("Y")));
			$where_man_days_ago["addtime"]=array("like",$days_ago."%");
			$where_man_days_ago["sex"]=1;
			$where_man_days_ago["proxy_id"]=$item["uid"];
			$where_man_days_ago["subscribe"]=1;
			$where_woman_days_ago["sex"]=2;
			$where_woman_days_ago["addtime"]=array("like",$days_ago."%");
			$where_woman_days_ago["proxy_id"]=$item["uid"];
			$where_woman_days_ago["subscribe"]=1;
			$data_days_ago["man"]+=$user->where($where_man_days_ago)->count();//大前天新增男性用户
			$data_days_ago["woman"]+=$user->where($where_woman_days_ago)->count();//大前天新增女性用户
			$data_days_ago["total"]+=$data_days_ago["man"]+$data_days_ago["woman"];//大前天新增用户总量
			$this->assign("user_days_ago",$data_days_ago);
			$this->assign("days_agonow",$days_ago);
			
			//大大前天统计
			$days_greatly=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-4,date("Y")));
			$where_man_days_greatly["addtime"]=array("like",$days_greatly."%");
			$where_man_days_greatly["sex"]=1;
			$where_man_days_greatly["proxy_id"]=$item["uid"];
			$where_man_days_greatly["subscribe"]=1;
			$where_woman_days_greatly["sex"]=2;
			$where_woman_days_greatly["addtime"]=array("like",$days_greatly."%");
			$where_woman_days_greatly["proxy_id"]=$item["uid"];
			$where_woman_days_greatly["subscribe"]=1;
			$data_days_greatly["man"]+=$user->where($where_man_days_greatly)->count();//大大前天新增男性用户
			$data_days_greatly["woman"]+=$user->where($where_woman_days_greatly)->count();//大大前天新增女性用户
			$data_days_greatly["total"]+=$data_days_greatly["man"]+$data_days_greatly["woman"];//大大前天新增用户总量
			$this->assign("user_days_greatly",$data_days_greatly);
			$this->assign("days_greatly",$days_greatly);
			
			//当月统计
			$daymonth=date("Y-m");
			$where_man_month["addtime"]=array("like",$daymonth."%");
			$where_man_month["sex"]=1;
			$where_man_month["proxy_id"]=$item["uid"];
			$where_man_month["subscribe"]=1;
			$where_woman_today["sex"]=2;
			$where_woman_today["addtime"]=array("like",$daymonth."%");
			$where_woman_today["proxy_id"]=$item["uid"];
			$where_woman_today["subscribe"]=1;
			$data_month["man"]+=$user->where($where_man_month)->count();//当月新增男性用户
			$data_month["woman"]+=$user->where($where_woman_today)->count();//当月新增女性用户
			$data_month["total"]+=$data_month["man"]+$data_month["woman"];//当月新增用户总量
			$this->assign("added_month",$data_month);
			
			//累计统计
			$where_man_overall["sex"]=1;
			$where_man_overall["proxy_id"]=$item["uid"];
			$where_man_overall["subscribe"]=1;
			$where_woman_overall["sex"]=2;
			$where_woman_overall["proxy_id"]=$item["uid"];
			$where_woman_overall["subscribe"]=1;
			$data_overall["man"] += $user->where($where_man_overall)->count();//总共新增男性用户
			//echo $user->getLastSql();die;
			$data_overall["woman"] += $user->where($where_woman_overall)->count();//总共新增女性用户
			$data_overall["total"] += intval($data_overall["man"])+intval($data_overall["woman"]);//总共新增用户总量
			$this->assign("added_overall",$data_overall);
			
			// 			if(!empty($data_overall["total"])) {
			// 				print_r($item)."<br>";
			// 				print_r($data_overall);
			// 				die;
			// 			}
		}
		
		$this->display();
	}
	
	/**
	 * 经济人/媒体人我的结算
	 * */
	public function myjiesuan(){
		//用户总充值金额
		
		//判断他是否有下线
		$sub_member_list = D("member")->where(array("par_id"=>$_SESSION["uid"]))->select();
		
		
		if(!empty($sub_member_list)){//经纪人
			//总充值金额
			$order = D()->query("select format(sum(c.money) / 100,2) as money  from qw_member as a left join qw_user as b on a.uid = b.proxy_id left join qw_order as c on b.open_id = c.open_id where c.status =1 and par_id = ".$_SESSION["uid"]);
			
			$order_info["money"] = $order[0]["money"];
			//用户总充值
			$this->assign("all_money", $order_info["money"]);
			
			$scale_info = D()->query("select scale from qw_member where uid=".$_SESSION['uid']);
			$_SESSION["scale"] = $scale_info[0]['scale'];
			
			$_SESSION['jiesuan_all_money']  = (int)(str_replace(",","",$order_info["money"]) * $_SESSION["scale"]);
			//结算单总额
			$uid= D()->query("select scale from qw_member where uid=".$_SESSION['uid']);
			
			$this->assign("all_jiesuan_money", number_format(str_replace(",", "",$order_info["money"]) * $_SESSION["scale"], 2));
		}else{
			//统计媒体下全部金额
			//计算出在某个时段内媒体人推荐的用户
			$user_info = D()->query("select DISTINCT a.open_id from qw_user as a left join qw_order as b on a.open_id = b.open_id left join qw_member as c on a.proxy_id = c.uid where a.subscribe = 1 and 0 < (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) and (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) < c.limit_time * 3600 and b.status = 1 and proxy_id=".$_SESSION["uid"]);
			
			$user_openids = "";
			foreach($user_info as $key=>$item)
				$user_openids.= "'".$item["open_id"]."',";
				
				if(!empty($user_openids))
					$user_openids = substr($user_openids, 0, strlen($user_openids) - 1);
					
					$order_info = D()->query("select format(sum(b.money) / 100,2)  as money from qw_user as a left join qw_order as b on a.open_id = b.open_id left join qw_member as c on a.proxy_id = c.uid where 0 < (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) and (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) < c.limit_time * 3600 and b.status = 1 and proxy_id=".$_SESSION["uid"]);
					
					$order_info = $order_info[0];
					//用户总充值（在某个时间段）
					
					$this->assign("all_money", $order_info["money"]);
					
					$scale_info = D()->query("select scale from qw_member where uid=".$_SESSION['uid']);
					$_SESSION["scale"] = $scale_info[0]['scale'];
					
					//结算单总额
					$_SESSION['jiesuan_all_money']  = (int)(str_replace(",","",$order_info["money"]) * $_SESSION["scale"]);
					
					//结算单总额
					$this->assign("all_jiesuan_money", number_format(str_replace(",", "",$order_info["money"]) * $_SESSION["scale"], 2));
					
		}
		
		//已经结算金额
		$jiesuan_info = D("jiesuan")->field("format(sum(money), 2) as money")->where("uid = ".$_SESSION["uid"]." and status <> 3")->find();
		
		$jiesuan_money = $jiesuan_info["money"] ? $jiesuan_info["money"] : 0.00;

		
		//当结算比列降低时，员工也已经在前期提现过，这时出现未提现金额为负值
		if(intval(number_format(str_replace(",", "",$order_info["money"])* $_SESSION["scale"]  - str_replace(",", "",$jiesuan_money), 2)) < 0){
			//未提现金额
			$this->assign("no_jiesuan_money", number_format(0, 2));
		}else{
			$this->assign("no_jiesuan_money", number_format(str_replace(",", "",$order_info["money"])* $_SESSION["scale"]  - str_replace(",", "",$jiesuan_money), 2));
		}
		
		//提现中金额
		$jiesuan_now = D("jiesuan")->field("format(sum(money), 2) as money")->where("uid = ".$_SESSION["uid"]." and status = 1")->find();
		$jiesuan_now= $jiesuan_now["money"] ? str_replace(",", "",$jiesuan_now["money"]) : 0.00;
		$this->assign("jiesuan_now", number_format(str_replace(",", "",$jiesuan_now), 2));
		//已打款金额
		$jiesuan_end = D("jiesuan")->field("format(sum(money), 2) as money")->where("uid = ".$_SESSION["uid"]." and status = 2")->find();
		$jiesuan_end= $jiesuan_end["money"] ? $jiesuan_end["money"] : 0.00;
		$this->assign("jiesuan_end", number_format(str_replace(",", "",$jiesuan_end), 2));
		
		$status = $_GET["status"] ? $_GET["status"] : "pending";
		$this->assign("status", $status);
		//列表
		$p = $_GET["p"] ? $_GET["p"] : 1;
		$pagesize = 20;
		$list = array();
		if($status == "pending"){ //未体现列表，不用管
			
		}
		elseif($status == "withdrawing"){ //提现中列表
			$offset = $pagesize * ($p - 1);
			$count = D("jiesuan")->where("status = 1 and uid = ".$_SESSION["uid"])->count();
			$list = D("jiesuan")->where("status = 1 and uid = ".$_SESSION["uid"])->limit("$offset,$pagesize")->select();
		}
		elseif($status == "paid"){ //已经提现列表
			$offset = $pagesize * ($p - 1);
			$count = D("jiesuan")->where("status = 2 and uid = ".$_SESSION["uid"])->count();
			$list = D("jiesuan")->where("status = 2 and uid = ".$_SESSION["uid"])->limit("$offset,$pagesize")->select();
		}
		$page = new \Think\Page($count, $pagesize);
		$page = $page->show();
		if(!empty($list))
			$this->assign("list", $list);
			else
				$this->assign("list", 0);
				$this->assign("page", $page);
				
				$this->display();
	}
	
	/**
	 * 申请提现
	 * */
	public function addjiesuan(){
		if($_POST){
			//判断提现金额是数字
			if(!is_numeric($_POST["money"])){
				$this->error("金额不是数字");
			}
			
			//判断提现总金额不能大于结算单总金额
			$jiesuan_money = D("jiesuan")->field("sum(money) as money")->where("uid = ".$_SESSION["uid"]." and status <> 3")->find();
			//总共提现的金额
			$tixian_money = $jiesuan_money['money'] + $_POST["money"];
			
			if ( $tixian_money > (int)$_SESSION['jiesuan_all_money']) {
				$this->error("提现金额不能大于总提现额度");
			}
			
			//判断是否有多余10元的提现金额
			$order_all_money = 0;
			$jiesuan_all_money = 0;
			//判断他是否有下线
			$sub_member_list = D("member")->where(array("par_id"=>$_SESSION["uid"]))->select();
			if(!empty($sub_member_list)){  //经济人
				if(intval($_POST['money']) < 10)
					$this->error("至少要有10元才能进行提现");
					
			}
			else{ //媒体人
				
				if(intval($_POST['money']) < 10)
					$this->error("至少要有10元才能进行提现");
			}
			
			$user_info = D()->query("select user from qw_member where uid= ".$_SESSION['uid']);
			$user = $user_info[0]['user']; 
			//添加结算金额
			$data["jiesuan_date"] = date("Y-m-d");
			$data["money"] = $_POST["money"];
			$data["uid"] = $_SESSION["uid"];
			$data["user"] = $user;
			$data["status"] = 1;
			$data["scale"] = $_SESSION["scale"];
			$rs = D("jiesuan")->add($data);
			
			if($rs)
				$this->success("提现成功请等待审核通过","/ProxyNovel/myjiesuan");
				else
					$this->error("提现失败请与客服人员联系");
					
		}
		else
			$this->display();
	}
	
	/**
	 * 代理结算列表
	 * */
	public function proxyjiesuanlist(){
		//查询手下所有的人员ID
		$sub_list = D("member")->field("uid")->where("par_id=".$_SESSION["uid"])->select();
		
		$sub_member_ids = "";
		foreach($sub_list as $key=>$item)
			$sub_member_ids .= $item["uid"].",";
			
			if(strlen($sub_member_ids) > 0)
				$sub_member_ids = substr($sub_member_ids, 0, strlen($sub_member_ids) - 1);
				
	
				//---------------------代理总充值数额----------------------------------------------//
				$total_number = 0;
				foreach($sub_list as $sub){
					if ($_GET['start_date'] && $_GET['end_date']) {
						$start_time = strtotime($_GET['start_date']); //起始时间
						$end_time = strtotime($_GET['end_date']);   //截止时间
						$order_info = D()->query("select format(sum(b.money) / 100,2)  as money from qw_user as a left join qw_order as b on a.open_id = b.open_id left join qw_member as c on a.proxy_id = c.uid where 0 < (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) and (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) < c.limit_time * 3600 and unix_timestamp(b.paytime) >= $start_time and unix_timestamp(b.paytime) < $end_time and b.status = 1 and proxy_id=".$sub["uid"]);
					}else{
						$order_info = D()->query("select format(sum(b.money) / 100,2)  as money from qw_user as a left join qw_order as b on a.open_id = b.open_id left join qw_member as c on a.proxy_id = c.uid where 0 < (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) and (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) < c.limit_time * 3600 and b.status = 1 and proxy_id=".$sub["uid"]);
					}
					
					$total_number += intval(str_replace(",", "",$order_info[0]['money']));
					
				}
				
				$order_info["money"] = number_format($total_number,2);
				
				$this->assign("all_money", $order_info["money"]);
				//---------------------代理总充值数额----------------------------------------------//
				
				//---------------------代理结算总额----------------------------------------------//
				$jiesuan_total_number = 0;
				foreach($sub_list as $sub){
					if ($_GET['start_date'] && $_GET['end_date']) {
						$start_time = strtotime($_GET['start_date']); //起始时间
						$end_time = strtotime($_GET['end_date']);   //截止时间
						$order_info1 = D()->query("select format(sum(b.money) / 100 * c.scale,2)  as money from qw_user as a left join qw_order as b on a.open_id = b.open_id left join qw_member as c on a.proxy_id = c.uid where 0 < (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) and (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) < c.limit_time * 3600 and b.status = 1 and unix_timestamp(b.paytime) >= $start_time and unix_timestamp(b.paytime) < $end_time and proxy_id=".$sub["uid"]);
						
					}else{
						$order_info1 = D()->query("select format(sum(b.money) / 100 * c.scale,2)  as money from qw_user as a left join qw_order as b on a.open_id = b.open_id left join qw_member as c on a.proxy_id = c.uid where 0 < (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) and (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) < c.limit_time * 3600 and b.status = 1 and proxy_id=".$sub["uid"]);
					}
					
					$jiesuan_total_number += intval(str_replace(",", "",$order_info1[0]['money']));
					
				}
				$this->assign("all_jiesuan_money", number_format($jiesuan_total_number,2));
				//---------------------代理结算总额----------------------------------------------//

				//充值多少笔
				if ($_GET['start_date'] && $_GET['end_date']) {
					$start_time = strtotime($_GET['start_date']); //起始时间
					$end_time = strtotime($_GET['end_date']);   //截止时间
					$order_count = D()->query("select count(1) as count from qw_member as a left join qw_user as b on a.uid = b.proxy_id left join qw_order as c on b.open_id = c.open_id where  0 < (unix_timestamp(c.paytime) - unix_timestamp(c.addtime)) and (unix_timestamp(c.paytime) - unix_timestamp(c.addtime)) < a.limit_time * 3600 and c.status = 1 and unix_timestamp(c.paytime) >= $start_time and unix_timestamp(c.paytime) < $end_time and par_id = ".$_SESSION["uid"]);
				}else{
					$order_count = D()->query("select count(1) as count from qw_member as a left join qw_user as b on a.uid = b.proxy_id left join qw_order as c on b.open_id = c.open_id where 0 < (unix_timestamp(c.paytime) - unix_timestamp(c.addtime)) and (unix_timestamp(c.paytime) - unix_timestamp(c.addtime)) < a.limit_time * 3600 and c.status = 1 and par_id = ".$_SESSION["uid"]);
					
				}
				$order_count = $order_count[0]["count"];
				$this->assign("order_count", $order_count);

				
				//成本（媒体人的成本加上自己的成本）
				//媒体人成本
				$member_list = D()->query('select uid from qw_member where par_id = '.$_SESSION['uid']);
				$prime_cost = 0;
				
				//经纪人的比率
				$jingji_info = D()->query("select scale from qw_member where uid = ".$_SESSION['uid']);
				$jing_ji = $jingji_info[0]["scale"];
				
				
				foreach($member_list as $member){
					if ($_GET['start_date'] && $_GET['end_date']) {
						$start_time = strtotime($_GET['start_date']); //起始时间
						$end_time = strtotime($_GET['end_date']);   //截止时间
						//媒体人负责用户的充值
						$order_money = D()->query("select format(sum(b.money) / 100,2)  as money from qw_user as a left join qw_order as b on a.open_id = b.open_id left join qw_member as c on a.proxy_id = c.uid where  0 < (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) and (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) < c.limit_time * 3600 and b.status = 1 and unix_timestamp(b.paytime) >= $start_time and unix_timestamp(b.paytime) < $end_time and proxy_id=" .$member["uid"]);
						
						//媒体人各自的比率
						$meiti_info = D()->query("select scale from qw_member where par_id =".$_SESSION['uid']);
						$mei_ti = $meiti_info[0]["scale"];
						
						//计算媒体人成本
						$prime_cost += str_replace(",", "",$order_money[0]["money"])* $jing_ji * $mei_ti;
					}else{
						//媒体人负责用户的充值
						$order_money = D()->query("select format(sum(b.money) / 100,2)  as money from qw_user as a left join qw_order as b on a.open_id = b.open_id left join qw_member as c on a.proxy_id = c.uid where  0 < (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) and (unix_timestamp(b.paytime) - unix_timestamp(b.addtime)) < c.limit_time * 3600 and b.status = 1 and proxy_id=" .$member["uid"]);
						
						//媒体人各自的比率
						$meiti_info = D()->query("select scale from qw_member where par_id =".$_SESSION['uid']);
						$mei_ti = $meiti_info[0]["scale"];
						
						//计算媒体人成本
						$prime_cost += str_replace(",", "",$order_money[0]["money"])* $jing_ji * $mei_ti;
					}
					
				}
	
				
				//经济人成本
				$no_jing_ji = 1 - $jing_ji;

				$no_jing_ji_money = str_replace(",", "",$order_info["money"]) * $no_jing_ji;
				
				$prime_cost = $prime_cost + $no_jing_ji_money;
	

				
				//成本显示
				$this->assign("prime_cost", number_format($prime_cost,2));
				//利润
				$profit = number_format(str_replace(",", "", $order_info["money"]) - str_replace(",", "", $prime_cost), 2);
				$this->assign("profit", $profit);
				
				//----------------------------已经结算金额-------------------------------//
				$member_list = D()->query('select uid from qw_member where par_id = '.$_SESSION['uid']);
				$jiesuan_money = 0;
				foreach($member_list as $member){
					if ($_GET['start_date'] && $_GET['end_date']) {
						$start_time = strtotime($_GET['start_date']); //起始时间
						$end_time = strtotime($_GET['end_date']);   //截止时间
						$jiesuan_info = D("jiesuan")->field("format(sum(money), 2) as money")->where("uid = ".$member['uid']." and status <> 3 and unix_timestamp(jiesuan_date) >= $start_time and unix_timestamp(jiesuan_date) < $end_time")->find();
						$jiesuan_money += str_replace(",", "",$jiesuan_info["money"]);
					}else{
						$jiesuan_info = D("jiesuan")->field("format(sum(money), 2) as money")->where("uid = ".$member['uid']." and status <> 3")->find();
						$jiesuan_money += str_replace(",", "",$jiesuan_info["money"]);
					}
				}
				
				$jiesuan_money = number_format($jiesuan_money,2) ? number_format($jiesuan_money,2) : 0.00;
				
				$this->assign("no_jiesuan_money", number_format($jiesuan_total_number  - str_replace(",", "",$jiesuan_money), 2));
				
				
				//--------------提现中金额------------------------//
				$jiesuan_now = 0;
				foreach($sub_list as $sub){
					if ($_GET['start_date'] && $_GET['end_date']) {
						$start_time = strtotime($_GET['start_date']); //起始时间
						$end_time = strtotime($_GET['end_date']);   //截止时间
						$jiesuan_now_list = D("jiesuan")->field("format(sum(money), 2) as money")->where("uid = ".$sub['uid']." and status = 1 and unix_timestamp(jiesuan_date) >= $start_time and unix_timestamp(jiesuan_date) < $end_time")->find();
						$jiesuan_now += intval(str_replace(",", "",$jiesuan_now_list['money']));
					}else{
						$jiesuan_now_list = D("jiesuan")->field("format(sum(money), 2) as money")->where("uid = ".$sub['uid']." and status = 1")->find();
						$jiesuan_now += intval(str_replace(",", "",$jiesuan_now_list['money']));
					}
				}
				
			
				$this->assign("jiesuan_now", number_format(str_replace(",", "",$jiesuan_now), 2));
				//--------------提现中金额------------------------//
				
				//----------------------已打款金额------------------------//
				$jiesuan_end = 0;
				foreach($sub_list as $sub){
					if ($_GET['start_date'] && $_GET['end_date']) {
						$start_time = strtotime($_GET['start_date']); //起始时间
						$end_time = strtotime($_GET['end_date']);   //截止时间
						$jiesuan_end_list = D("jiesuan")->field("format(sum(money), 2) as money")->where("uid = " . $sub['uid'] . " and status = 2 and unix_timestamp(jiesuan_date) >= $start_time and unix_timestamp(jiesuan_date) < $end_time")->find();
						$jiesuan_end += intval(str_replace(",", "",$jiesuan_end_list['money']));
					}else {
						$jiesuan_end_list = D("jiesuan")->field("format(sum(money), 2) as money")->where("uid = " . $sub['uid'] . " and status = 2")->find();
						$jiesuan_end += intval(str_replace(",", "", $jiesuan_end_list['money']));
					}
				}
				
	
				$this->assign("jiesuan_end", number_format(str_replace(",", "",$jiesuan_end), 2));
				//----------------------已打款金额------------------------//
				
				if ($_GET['start_date'] && $_GET['end_date']) {
					$start_time = strtotime($_GET['start_date']); //起始时间
					$end_time = strtotime($_GET['end_date']);   //截止时间
					$this->assign("start_time", $start_time);
					$this->assign("end_time", $end_time);
				}
				
				$status = $_GET["status"] ? $_GET["status"] : "pending";
				$this->assign("status", $status);
				
				
				//列表
				$p = $_GET["p"] ? $_GET["p"] : 1;
				$pagesize = 20;
				$list = array();
				
				
				if(!empty($sub_list[0]["uid"])) {
					
					
					if($status == "pending"){ //未体现列表，不用管
						
					}
					elseif($status == "withdrawing"){ //提现中列表
						$offset = $pagesize * ($p - 1);
						if ($_GET['start_date'] && $_GET['end_date']) {
							$start = strtotime($_GET['start_date']);
							$end = strtotime($_GET['end_date']);
							$count = D("jiesuan")->where("status = 1 and uid in ($sub_member_ids) and unix_timestamp(jiesuan_date) >= $start and unix_timestamp(jiesuan_date) < $end")->count();
							$list = D("jiesuan")->where("status = 1 and uid in ($sub_member_ids) and unix_timestamp(jiesuan_date) >= $start and unix_timestamp(jiesuan_date) < $end")->limit("$offset,$pagesize")->select();
							
						}else{
							$count = D("jiesuan")->where("status = 1 and uid in ($sub_member_ids)")->count();
							$list = D("jiesuan")->where("status = 1 and uid in ($sub_member_ids)")->limit("$offset,$pagesize")->select();
						}
					}
					elseif($status == "paid"){ //已经提现列表
						$offset = $pagesize * ($p - 1);
						if ($_GET['start_date'] && $_GET['end_date']) {
							$start = strtotime($_GET['start_date']);
							$end = strtotime($_GET['end_date']);
							$count = D("jiesuan")->where("status = 2 and uid in ($sub_member_ids) and unix_timestamp(jiesuan_date) >= $start and unix_timestamp(jiesuan_date) < $end")->count();
							$list = D("jiesuan")->where("status = 2 and uid in ($sub_member_ids) and unix_timestamp(jiesuan_date) >= $start and unix_timestamp(jiesuan_date) < $end")->limit("$offset,$pagesize")->select();
						}else {
							$count = D("jiesuan")->where("status = 2 and uid in ($sub_member_ids)")->count();
							$list = D("jiesuan")->where("status = 2 and uid in ($sub_member_ids)")->limit("$offset,$pagesize")->select();
						}
					}
					
					$page = new \Think\Page($count, $pagesize);
					$page = $page->show();
					if(!empty($list))
						$this->assign("list", $list);
						else
							$this->assign("list", 0);
							
							$this->assign("page", $page);
				}
				else{
					$this->assign("list", 0);
				}
				
				//查询时间
				$this->assign("today",date("Y-m-d"));
				
				$this->display();
	}
	
	
	
	/**
	 * 已打款
	 * */
	public function jiesuanstatuschange(){
		$id  = $_GET['id'];
		$change = D()->execute("update qw_jiesuan set status = 2 where id = ".$id);
		$this->success('打款成功', '/ProxyNovel/proxyjiesuanlist');
	}

}